package com.app.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import com.app.common.EducationTool;
import com.app.mapper.MatchingSuccessfulMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.DateUtil;
import com.app.util.Result;
import com.app.vo.CustomerListVo;
import com.app.vo.EnterpriseVo;
import com.app.vo.MatchingSuccessfulVo;
import com.app.vo.WorkApplyVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@Controller
@Slf4j
public class ScreenListController {
    @Autowired
    private QuestionnaireInvestigationService questionnaireInvestigationService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private JobPublishService jobPublishService;
    @Autowired
    private JobIntentionService jobIntentionService;
    @Resource
    private SkillTrainingService skillTrainingService;
    @Resource
    private VideoTrainService videoTrainService;
    @Resource
    private TrainEnrollService trainEnrollService;
    @Resource
    private StreetService streetService;
    @Resource
    private ConfigService configService;
    @Resource
    private WorkApplyService workApplyService;
    @Resource
    private BrowseNumberService browseNumberService;
    @Resource
    private CustomerService customerService;
    @Resource
    private UserService userService;
    @Resource
    private ComRecruitersService comRecruitersService;
    @Resource
    private MatchingSuccessfulMapper matchingSuccessfulMapper;

    //乡镇列表
    @GetMapping("/villageList")
    public Result<Object> villageList() {
        List<ConfigModel> list = (List<ConfigModel>) configService.villageList();
        return Result.success(findChildren(list, 0));
    }

    //街道列表
    @GetMapping("/streetList")
    public Result<Object> streetList() {
        List<ConfigModel> list = (List<ConfigModel>) configService.streetList();
        return Result.success(findChildren(list, 0));
    }

    private List<ConfigModel> findChildren(List<ConfigModel> modelList, Integer pid) {//递归方法
        List<ConfigModel> personModelList = new ArrayList<>();
        for (int i = 0; i < modelList.size(); i++) {
            if (Objects.equals(modelList.get(i).getFatherId(), pid)) {
                ConfigModel model = modelList.get(i);
                List<ConfigModel> modelList1 = findChildren(modelList, model.getId());
                for (int j = 0; j < modelList1.size(); j++) {
                    if (modelList1 != null && modelList1.size() > 0) {
                        model.setChild(modelList1);
                    }
                }
                personModelList.add(model);
            }
        }
        return personModelList;
    }

    //农村劳动力列表
    @GetMapping("/ruralList")
    public Result<Object> ruralList(Integer page, Integer limit, @RequestParam(required = false) Integer streetId) {
        Page<QuestionnaireInvestigationModel> questionnaireInvestigationModelPage=questionnaireInvestigationService.ruralList(page, limit, streetId);
        if(ObjectUtil.isNotEmpty(questionnaireInvestigationModelPage.getRecords()))
        {
            for (QuestionnaireInvestigationModel q:questionnaireInvestigationModelPage.getRecords()
                 ) {
                try {
                    q.setMobile(DesensitizedUtil.mobilePhone(q.getMobile()));
                } catch (Exception e)
                {
                    log.error("手机号脱敏失败");
                }
                try {
                    q.setRealName(DesensitizedUtil.chineseName(q.getRealName()));
                } catch (Exception e)
                {
                    log.error("姓名脱敏失败");
                }

            }
        }
        return Result.success(questionnaireInvestigationModelPage);
    }

    //城镇未就业列表
    @GetMapping("/unemployedList")
    public Result<Object> unemployedList(Integer page, Integer limit, Integer streetId) {

        Page<QuestionnaireInvestigationModel> unemployedList = questionnaireInvestigationService.unemployedList(page, limit, streetId);
        if (CollectionUtil.isNotEmpty(unemployedList.getRecords())) {
            for (QuestionnaireInvestigationModel q : unemployedList.getRecords()
            ) {
                try {
                    q.setRealName(DesensitizedUtil.chineseName(q.getRealName()));
                } catch (Exception e) {

                }
                try {
                    q.setMobile(DesensitizedUtil.mobilePhone(q.getMobile()));

                } catch (Exception e) {

                }
            }
        }
        return Result.success(unemployedList);
    }

    //城镇有就业意愿列表
    @GetMapping("/intentionsList")
    public Result<Object> intentionsList(Integer page, Integer limit, Integer streetId) {
        Page<QuestionnaireInvestigationModel> unemployedList = questionnaireInvestigationService.intentionsList(page, limit, streetId);
        if (CollectionUtil.isNotEmpty(unemployedList.getRecords())) {
            for (QuestionnaireInvestigationModel q : unemployedList.getRecords()
            ) {
                try {
                    q.setRealName(DesensitizedUtil.chineseName(q.getRealName()));

                } catch (Exception e) {

                }
                try {
                    q.setMobile(DesensitizedUtil.mobilePhone(q.getMobile()));

                } catch (Exception e) {

                }
            }
        }
        return Result.success(unemployedList);
    }

    //用人单位列表
    @GetMapping("/employersList")
    public Result<Object> employersList(Integer page, Integer limit) {
        Page<EnterpriseModel> enterpriseModels = enterpriseService.employersList(page, limit);
        List<EnterpriseModel> collect = enterpriseModels.getRecords();
        if (CollectionUtil.isNotEmpty(collect)) {
            for (EnterpriseModel e : collect
            ) {
                try {
                    e.setLegalPersonName(DesensitizedUtil.chineseName(e.getLegalPersonName()));
                } catch (Exception exception) {
                    log.error(exception.getMessage());
                }

            }
        }

        return Result.success(enterpriseModels);
    }

    //在招岗位列表
    @GetMapping("/postList")
    public Result<Object> postList(Integer page, Integer limit) {
        return Result.success(jobPublishService.postList(page, limit));
    }

    //全部岗位列表
    @GetMapping("/allPostList")
    public Result<Object> allPostList(Integer page, Integer limit) {
        return Result.success(jobPublishService.allPostList(page, limit));
    }

    //求职人数列表 街道
    @GetMapping("/seekersList")
    public Result<Object> seekersList(Integer page, Integer limit, @RequestParam(required = false) Integer streetId) {

        Page<JobIntentionModel> enterpriseModels = jobIntentionService.seekersList(page, limit, streetId);
        List<JobIntentionModel> collect = enterpriseModels.getRecords();
        if (CollectionUtil.isNotEmpty(collect)) {
            for (JobIntentionModel e : collect
            ) {
                try {
                    e.getCustomer().setRealName(DesensitizedUtil.chineseName(e.getCustomer().getRealName()));
                } catch (Exception exception) {
                    log.error(exception.getMessage());
                }
                try {
                    e.getCustomer().setMobile(DesensitizedUtil.mobilePhone(e.getCustomer().getMobile()));
                } catch (Exception exception) {
                    log.error(exception.getMessage());
                }
            }
        }


        return Result.success(enterpriseModels);
    }

    //简历投递人列表 街道
    @GetMapping("/resumeList")
    public Result<Object> resumeList(Integer page, Integer limit, Integer streetId) {


        WorkApplyVo enterpriseModels = workApplyService.resumeList(page, limit, streetId);
        List<WorkApplyModel> collect = enterpriseModels.getList();
        if (CollectionUtil.isNotEmpty(collect)) {
            for (WorkApplyModel e : collect
            ) {
                try {
                    e.getCustomer().setRealName(DesensitizedUtil.chineseName(e.getCustomer().getRealName()));
                } catch (Exception exception) {
                    log.error(exception.getMessage());
                }
                try {
                    e.getCustomer().setMobile(DesensitizedUtil.mobilePhone(e.getCustomer().getMobile()));
                } catch (Exception exception) {
                    log.error(exception.getMessage());
                }
            }
        }

        return Result.success(enterpriseModels);
    }

    //报名人数列表
    @GetMapping("/registrationList")
    public Result<Object> registrationList(Integer page, Integer limit, Integer streetId) {
        return Result.success(trainEnrollService.registrationList(page, limit, streetId));
    }

    //培训机构列表 街道
    @GetMapping("/trainList")
    public Result<Object> trainList(Integer page, Integer limit) {
        return Result.success(skillTrainingService.selectTrainList(page, limit));
    }

    //培训课程列表
    @GetMapping("/courseList")
    public Result<Object> courseList(Integer page, Integer limit) {
        return Result.success(videoTrainService.courseList(page, limit));
    }

    //工种列表
    @GetMapping("/typeWorkList")
    public Result<Object> typeWorkList(Integer page, Integer limit) {
        return null;
    }

    //所有公司列表
    @GetMapping("/enterprise")
    public Result<Object> enterprise(Integer page, Integer limit, @RequestParam(required = false) Integer streetId) {
        Page<EnterpriseModel> enterpriseModels = enterpriseService.employersList(page, limit);
        List<EnterpriseModel> collect = enterpriseModels.getRecords();
        if (CollectionUtil.isNotEmpty(collect)) {
            for (EnterpriseModel e : collect
            ) {
                try {
                    e.setLegalPersonName(DesensitizedUtil.chineseName(e.getLegalPersonName()));
                } catch (Exception exception) {
                    log.error(exception.getMessage());
                }

            }
        }
        EnterpriseVo vo = new EnterpriseVo();
        vo.setList(collect);
        vo.setCount((int) enterpriseModels.getTotal());
        return Result.success(vo);
    }


    //访问量列表 街道
    @GetMapping("/browseNumber")
    public Result<Object> browseNumber(Integer page, Integer limit) {
        List<BrowseNumberModel> browseNumberModels = browseNumberService.selectAll(page, limit);
        for (int i = 0; i < browseNumberModels.size(); i++) {
            if (browseNumberModels.get(i).getUserId() != 0) {
                UserModel userById = userService.getUserById(browseNumberModels.get(i).getUserId());
                if (userById != null) {
                    if (userById.getCId() != null && userById.getCId() != 0) {
                        CustomerModel customerById = customerService.getCustomerById(userById.getCId());
                        if (customerById != null) {
                            browseNumberModels.get(i).setUserName(customerById.getRealName());
                            browseNumberModels.get(i).setMobile(userById.getMobile());
                            browseNumberModels.get(i).setBirthday(customerById.getBirthday());
                            if (customerById.getSex() == 1) {
                                browseNumberModels.get(i).setSex("男");
                            }
                            if (customerById.getSex() == 2) {
                                browseNumberModels.get(i).setSex("女");
                            }
                        }
                    }
                    if (userById.getRId() != null && userById.getRId() != 0) {
                        ComRecruitersModel comRecruitersById = comRecruitersService.getComRecruitersById(userById.getRId());
                        if (comRecruitersById != null) {
                            browseNumberModels.get(i).setUserName(comRecruitersById.getRealName());
                            browseNumberModels.get(i).setMobile(userById.getMobile());
                        }
                    }
                }
            }
        }
        return Result.success(browseNumberModels);
    }

    //所有用户
    @GetMapping("/customer")
    public Result<Object> customer(Integer page, Integer limit, Integer streetId) {
        List<CustomerModel> customerList = customerService.selectAll(page, limit, streetId);
        int count = customerService.selectAllCount(streetId);
        CustomerListVo vo = new CustomerListVo();
        vo.setList(customerList);
        vo.setCount(count);
        return Result.success(vo);
    }

    //匹配成功数列表
    @GetMapping("/matchingSuccessfulList")
    public Result<Object> matchingSuccessfulList(Integer page, Integer limit) throws ParseException {
        page = (page - 1) * limit;
        List<MatchingSuccessfulModel> matchingSuccessfulModels = matchingSuccessfulMapper.matchingSuccessfulList(page, limit);
        if (matchingSuccessfulModels != null && !matchingSuccessfulModels.isEmpty()) {
            for (int i = 0; i < matchingSuccessfulModels.size(); i++) {
                if (matchingSuccessfulModels.get(i).getSex() == 1) {
                    matchingSuccessfulModels.get(i).setSexText("男");
                } else {
                    matchingSuccessfulModels.get(i).setSexText("女");
                }
                for (int i1 = 0; i1 < EducationTool.EDUCATION_VO_LIST.size(); i1++) {
                    if (matchingSuccessfulModels.get(i).getEduction() != null && matchingSuccessfulModels.get(i).getEduction() == EducationTool.EDUCATION_VO_LIST.get(i1).getId()) {
                        matchingSuccessfulModels.get(i).setEductionText(EducationTool.EDUCATION_VO_LIST.get(i1).getData());
                    } else {
                        matchingSuccessfulModels.get(i).setEductionText("暂无");
                    }
                }
                if (matchingSuccessfulModels.get(i).getBirthday() != null) {
                    Timestamp time = new Timestamp(new SimpleDateFormat("yyyy-MM-dd").parse(matchingSuccessfulModels.get(i).getBirthday() + "-01").getTime());
                    String date = DateUtil.yearCompare(time, CommonHelp.getNowTimestamp());
                    matchingSuccessfulModels.get(i).setAge(Integer.valueOf(date));
                } else {
                    matchingSuccessfulModels.get(i).setAge(0);
                }
            }
        }
        Integer count = matchingSuccessfulMapper.selectCount();
        MatchingSuccessfulVo vo = new MatchingSuccessfulVo();
        vo.setList(matchingSuccessfulModels);
        vo.setCount(count);
        return Result.success(vo);
    }
}